package product;

import java.awt.*;
import java.awt.event.*;
import java.text.*;
import java.util.*;
import java.util.List;

import javax.swing.*;
import javax.swing.border.*;
import javax.swing.table.*;

import net.miginfocom.swing.*;

public class DeliveryInput2 extends JInternalFrame {
	Map<Long, DeliveryData> delivery = new HashMap<>();
	Map<String, CompanyData> customer = new HashMap<>();

	boolean flag = false;
	Long oriTotal;
	
	Object[] row = {null, null, Integer.valueOf(0), null};
	
	TableColumnModel colModel;
	DecimalFormat df = new DecimalFormat("###,###,###,###,### 원");
	DefaultTableModel model = new DefaultTableModel(
			new Object[][] {{null, null, Integer.valueOf(0), null}},
			new String[] {"\uD488\uBA85", "\uB2E8\uAC00", 
					"\uC218\uB7C9", "\uC9C0\uBD88\uAE08\uC561"}) {
		
		private static final long serialVersionUID = 1L;
		Class[] columnTypes = new Class[] {
				String.class, Long.class, Long.class, Long.class
		};
		boolean[] columnEditables = new boolean[] {
				true, true, true, false
		};
		@Override
		public Class getColumnClass(int columnIndex) {
			return columnTypes[columnIndex];
		}
	};
	
	private JLabel lblNewLabel;
	private JLayeredPane layeredPane;
	private JTextField inputCode;
	private JLabel lblNewLabel_1;
	private JTextField inputName;
	private JLabel lblNewLabel_2;
	private JTextField inputCEO;
	private JLabel lblLogo;
	private JButton btnCodeSearch;
	private JSeparator separator;
	private JButton btnSave;
	private JButton btnCancel;
	private JButton btnReset;
	private JTextField inputData;
	private JButton btnNewButton;
	private JButton btnNewButton_1;
	private JButton btnSearch1;

	private JSpinner spinner1;
	private JSpinner spinner2;
	private JSpinner spinner3;
	private JSpinner spinner4;
	private JSpinner spinner5;
	private JLayeredPane layeredPane_1;
	private JPanel panel;
	private JButton btnNewButton_2;
	private JButton btnNewButton_3;
	private JScrollPane scrollPane_1;
	private JTable table;
	private JButton btnNewButton_4;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			@Override
			public void run() {
				try {
					DeliveryInput2 frame = new DeliveryInput2();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public DeliveryInput2() {
		super("납품 추가", true, true, true, false);
		setBounds(0, 310, 450, 452);
		getContentPane().setLayout(null);
		getContentPane().add(getLayeredPane_1());
		getContentPane().add(getBtnSave());
		getContentPane().add(getBtnCancel());
		getContentPane().add(getBtnReset());
		getContentPane().add(getLayeredPane_1_1());
	}

	public void setC(Map d, Map c) {
		this.delivery = d;
		this.customer = c;
	}

	// 테이블의 값이 변경되면 단가와 수량으로 지불금액을 자동 계산
	public void compute() {
		try {
			for(int i = 0; i < table.getRowCount(); i++){
				String price = table.getValueAt(i, 1).toString();
				String ea = table.getValueAt(i, 2).toString();

				// 단가와 수량의 값이 있을 경우에만 계산 
				if(!price.equals("") && !ea.equals("")){
					oriTotal = (Long.parseLong(price) * Long.parseLong(ea));
					table.setValueAt(oriTotal, i, 3);
				}
			}
		} catch (Exception ex) {
			JOptionPane.showMessageDialog(null, "단가와 수량에는 숫자만 입력하세요.");
		}
	}

	private JLabel getLblNewLabel() {
		if (lblNewLabel == null) {
			lblNewLabel = new JLabel("사업자번호");
			lblNewLabel.setPreferredSize(new Dimension(70, 20));
		}
		return lblNewLabel;
	}

	private JLayeredPane getLayeredPane_1() {
		if (layeredPane == null) {
			layeredPane = new JLayeredPane();
			layeredPane.setBorder(new EtchedBorder(EtchedBorder.RAISED, null,
					null));
			layeredPane.setBounds(12, 10, 410, 155);
			layeredPane
					.setLayout(new MigLayout("", "[61.00px][][56.00px,grow][34.00][47.00][51.00][18.00,grow][90.00,grow]", "[28.00][16.00][15.00][28][28]"));
			layeredPane.add(getInputData(), "cell 0 0 6 1,growx");
			layeredPane.add(getBtnSearch1(), "cell 7 0");
			layeredPane.add(getSeparator(), "cell 0 1 8 1,growx");
			layeredPane.add(getLblNewLabel(), "cell 0 2,grow");
			layeredPane.add(getInputCode(), "cell 2 2 4 1,growx,aligny center");
			layeredPane.add(getLblNewLabel_1(), "cell 0 3,grow");
			layeredPane.add(getInputName(), "cell 2 3 4 1,growx,aligny center");
			layeredPane.add(getLblNewLabel_2(), "cell 0 4,alignx left,growy");
			layeredPane.add(getInputCEO(), "cell 2 4 4 1,growx,aligny center");
			layeredPane.add(getLblLogo(), "cell 7 2 1 3,grow");
		}
		return layeredPane;
	}

	private JTextField getInputCode() {
		if (inputCode == null) {
			inputCode = new JTextField();
			inputCode.setEnabled(false);
			inputCode.setPreferredSize(new Dimension(150, 21));
			inputCode.setColumns(10);
		}
		return inputCode;
	}

	private JLabel getLblNewLabel_1() {
		if (lblNewLabel_1 == null) {
			lblNewLabel_1 = new JLabel("회사명");
		}
		return lblNewLabel_1;
	}

	private JTextField getInputName() {
		if (inputName == null) {
			inputName = new JTextField();
			inputName.setEnabled(false);
			inputName.setColumns(10);
		}
		return inputName;
	}

	private JLabel getLblNewLabel_2() {
		if (lblNewLabel_2 == null) {
			lblNewLabel_2 = new JLabel("대표자명");
		}
		return lblNewLabel_2;
	}

	private JTextField getInputCEO() {
		if (inputCEO == null) {
			inputCEO = new JTextField();
			inputCEO.setEnabled(false);
			inputCEO.setColumns(10);
		}
		return inputCEO;
	}

	private JLabel getLblLogo() {
		if (lblLogo == null) {
			lblLogo = new JLabel("");
			lblLogo.setHorizontalAlignment(SwingConstants.CENTER);
			lblLogo.setBorder(new LineBorder(new Color(0, 0, 0)));
		}
		return lblLogo;
	}

	private JSeparator getSeparator() {
		if (separator == null) {
			separator = new JSeparator();
			separator.setBackground(new Color(255, 255, 255));
			separator.setOpaque(true);
			separator.setForeground(new Color(0, 0, 0));
			separator.setBorder(new EtchedBorder(EtchedBorder.RAISED, null, null));
		}
		return separator;
	}

	private JButton getBtnSave() {
		if (btnSave == null) {
			btnSave = new JButton("저장");
			btnSave.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent e) {
					long index = 0;
					
					// HashMap의 아무 값도 없다면 0번째에 저장하기 위해 index값을 -1로 셋팅
					if (delivery.size() == 0) {
						index = 0;
						
 					// HashMap에 어떤 값이 들어있다면 Key값을 List에 저장해서 정렬
					// 납품번호는 항상 HashMap에 저장된 가장 큰 값보다 1 큰 값으로 저장
					}else{
						List<Long> list = new ArrayList<>();
						list.addAll(delivery.keySet());
						Collections.sort(list);
						
						index = list.get(list.size() - 1) + 1;
					}
							
					// 테이블에 입력한 값들을 Hash맵에 차곡차곡 저장
					for(int i = 0; i < table.getRowCount(); i++){						
						String name = table.getValueAt(i, 0).toString();
						String price = table.getValueAt(i, 1).toString();
						String ea = table.getValueAt(i, 2).toString();
						String total = table.getValueAt(i, 3).toString();

						if(name.equals("") || price.equals("") || ea.equals("")) continue;
						
						DeliveryData dd = new DeliveryData(name, price, ea, inputName.getText(), inputCEO.getText(), inputCode.getText());
						dd.setComNumber("" + index + i);
						dd.setTotPrice(Long.parseLong(total));
	
						delivery.put(index + i, dd);
					}
					
					JOptionPane.showMessageDialog(null, "자~~알 저장되었습니다.");

					inputCode.setText("");
					inputName.setText("");
					inputCEO.setText("");
					inputData.setText("");
					lblLogo.setIcon(new ImageIcon());
					model.setNumRows(0);
				}
			});
			btnSave.setBounds(216, 370, 206, 40);
		}
		return btnSave;
	}

	private JButton getBtnCancel() {
		if (btnCancel == null) {
			btnCancel = new JButton("취소");
			btnCancel.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent e) {
					int yn = JOptionPane
							.showConfirmDialog(null, "창을 닫으시겠습니까??");
					if (yn == JOptionPane.OK_OPTION) {
						inputCode.setText("");
						inputName.setText("");
						inputCEO.setText("");
						inputData.setText("");
						lblLogo.setIcon(new ImageIcon());
						model.setNumRows(0);

						setVisible(false);
					}
				}
			});
			btnCancel.setBounds(114, 370, 90, 40);
		}
		return btnCancel;
	}

	private JButton getBtnReset() {
		if (btnReset == null) {
			btnReset = new JButton("다시작성");
			btnReset.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent e) {
					int yn = JOptionPane.showConfirmDialog(null,
							"다시 작성 하시겠습니까??");
					if (yn == JOptionPane.OK_OPTION) {
						inputCode.setText("");
						inputName.setText("");
						inputCEO.setText("");
						inputData.setText("");
						lblLogo.setIcon(new ImageIcon());
						model.setNumRows(0);
					}
				}
			});
			btnReset.setBounds(12, 370, 90, 40);
		}
		return btnReset;
	}

	private JTextField getInputData() {
		if (inputData == null) {
			inputData = new JTextField();
			inputData.setColumns(10);
		}
		return inputData;
	}

	private JButton getBtnSearch1() {
		if (btnSearch1 == null) {
			btnSearch1 = new JButton("거래처 조회");
			btnSearch1.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent e) {
					Iterator<String> it = customer.keySet().iterator();
					while (it.hasNext()) {
						String key = it.next();
						if (inputData.getText().equals(customer.get(key).getCode())
								|| inputData.getText().equals(customer.get(key).getName())
								|| inputData.getText().equals(customer.get(key).getCeo())) {

							inputCode.setText(customer.get(key).getCode());
							inputName.setText(customer.get(key).getName());
							inputCEO.setText(customer.get(key).getCeo());
							lblLogo.setIcon(new ImageIcon("/logoImg/" + customer.get(key).getCode() + ".png"));

							break;
						}
					}
				}
			});
		}
		return btnSearch1;
	}
	private JLayeredPane getLayeredPane_1_1() {
		if (layeredPane_1 == null) {
			layeredPane_1 = new JLayeredPane();
			layeredPane_1.setBounds(12, 175, 410, 185);
			layeredPane_1.setLayout(new BorderLayout(10, 0));
			layeredPane_1.add(getPanel_1(), BorderLayout.EAST);
			layeredPane_1.add(getScrollPane_1(), BorderLayout.CENTER);
		}
		return layeredPane_1;
	}
	private JPanel getPanel_1() {
		if (panel == null) {
			panel = new JPanel();
			panel.setLayout(new GridLayout(5, 1, 10, 5));
			panel.add(getBtnNewButton_2());
			panel.add(getBtnNewButton_3());
			panel.add(getBtnNewButton_4());
		}
		return panel;
	}
	private JButton getBtnNewButton_2() {
		if (btnNewButton_2 == null) {
			btnNewButton_2 = new JButton("행 추가");
			btnNewButton_2.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent arg0) {
					model.addRow(row);
					colModel.getColumn(2).setCellEditor(new SpinnerEditor());
				}
			});
		}
		return btnNewButton_2;
	}
	private JButton getBtnNewButton_3() {
		if (btnNewButton_3 == null) {
			btnNewButton_3 = new JButton("행 삭제");
			btnNewButton_3.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent arg0) {
					model.removeRow(table.getRowCount() - 1);
				}
			});
		}
		return btnNewButton_3;
	}
	private JScrollPane getScrollPane_1() {
		if (scrollPane_1 == null) {
			scrollPane_1 = new JScrollPane();
			scrollPane_1.setBorder(null);
			scrollPane_1.setViewportView(getTable());
		}
		return scrollPane_1;
	}
	private JTable getTable() {
		if (table == null) {	
			table = new JTable(model);
			
			// 테이블에 단가와 수량을 입력할 때마다 지불금액을 계산
			table.addKeyListener(new KeyAdapter() {
				@Override
				public void keyReleased(KeyEvent arg0) {
					compute(); 
				}
			});
			table.setGridColor(Color.LIGHT_GRAY);
			
			// 테이블의 '수량'을 입력할 때 JSpinner를 이용
			colModel = table.getColumnModel();
			colModel.getColumn(2).setCellEditor(new SpinnerEditor());
		}
		return table;
	}
	private JButton getBtnNewButton_4() {
		if (btnNewButton_4 == null) {
			btnNewButton_4 = new JButton("지우기");
		}
		return btnNewButton_4;
	}
}
//class SpinnerEditor extends DefaultCellEditor
//{
//    JSpinner spinner;
//    JSpinner.DefaultEditor editor;
//    JTextField textField;
//    boolean valueSet;
//
//    // Initializes the spinner.
//    public SpinnerEditor() {
//        super(new JTextField());
//        spinner = new JSpinner();
//        editor = ((JSpinner.DefaultEditor)spinner.getEditor());
//        textField = editor.getTextField();
//        textField.addFocusListener( new FocusListener() {
//            public void focusGained( FocusEvent fe ) {
//                System.err.println("Got focus");
//                //textField.setSelectionStart(0);
//                //textField.setSelectionEnd(1);
//                SwingUtilities.invokeLater( new Runnable() {
//                    public void run() {
//                        if ( valueSet ) {
//                            textField.setCaretPosition(1);
//                        }
//                    }
//                });
//            }
//            public void focusLost( FocusEvent fe ) {
//            }
//        });
//        textField.addActionListener( new ActionListener() {
//            public void actionPerformed( ActionEvent ae ) {
//                stopCellEditing();
//            }
//        });
//    }
//
//    // Prepares the spinner component and returns it.
//    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
//        if ( !valueSet ) {
//            spinner.setValue(value);
//        }
//        SwingUtilities.invokeLater( new Runnable() {
//            public void run() {
//                textField.requestFocus();
//            }
//        });
//        return spinner;
//    }
//
//    public boolean isCellEditable( EventObject eo ) {
//        System.err.println("isCellEditable");
//        if ( eo instanceof KeyEvent ) {
//            KeyEvent ke = (KeyEvent)eo;
//            System.err.println("key event: "+ke.getKeyChar());
//            textField.setText(String.valueOf(ke.getKeyChar()));
//            //textField.select(1,1);
//            //textField.setCaretPosition(1);
//            //textField.moveCaretPosition(1);
//            valueSet = true;
//        } else {
//            valueSet = false;
//        }
//        return true;
//    }
//
//    // Returns the spinners current value.
//    public Object getCellEditorValue() {
//        return spinner.getValue();
//    }
//
//    public boolean stopCellEditing() {
//        System.err.println("Stopping edit");
//        try {
//            editor.commitEdit();
//            spinner.commitEdit();
//        } catch ( java.text.ParseException e ) {
//            JOptionPane.showMessageDialog(null, "Invalid value, discarding.");
//        }
//        return super.stopCellEditing();
//    }
//}
class SpinnerEditor extends AbstractCellEditor implements TableCellEditor {

    private static final long serialVersionUID = 1L;
    private SpinnerNumberModel model = new SpinnerNumberModel(0, 0, null, 1);
    private JSpinner spinner = new JSpinner(model);
    private int clickCountToStart = 1;

    @Override
	public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
        spinner.setValue(((Integer) value).intValue());
        return spinner;
    }

    @Override
	public Object getCellEditorValue() {
        return spinner.getValue();
    }

    @Override
    public boolean isCellEditable(EventObject anEvent) {
        if (anEvent instanceof MouseEvent) {
            return ((MouseEvent) anEvent).getClickCount() >= clickCountToStart;
        }
        return true;
    }

    @Override
    public boolean shouldSelectCell(EventObject anEvent) {
        return true;
    }

    @Override
    public boolean stopCellEditing() {
        return super.stopCellEditing();
    }

    @Override
    public void cancelCellEditing() {
        super.cancelCellEditing();
    }
}